package com.example.audiostreaming.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.audiostreaming.R;
import com.example.audiostreaming.adapters.AdapterAlbumRv;
import com.example.audiostreaming.adapters.AdapterSuggestWordRv;
import com.example.audiostreaming.base.BaseActivity;
import com.example.audiostreaming.implement.ImplDetailLogic;
import com.example.audiostreaming.implement.ImplSearchLogic;
import com.example.audiostreaming.interfaces.ISearchViewCallback;
import com.example.audiostreaming.utils.UtilLog;
import com.example.audiostreaming.utils.UtilUI;
import com.example.audiostreaming.views.ViewFlowTextLayout;
import com.example.audiostreaming.views.ViewUILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.example.audiostreaming.base.BaseApplication.getAppContext;
import static com.example.audiostreaming.base.BaseApplication.getHandler;

/**
 * 搜索界面
 */
public class SearchActivity extends BaseActivity {
    private static final String TAG = "SearchActivity";


    private EditText mSearchInput;
    private TextView mSearchBtn;
    private FrameLayout mSearchContainer;
    private ImplSearchLogic mImplSearchLogic;
    private SearchViewCallback mSearchViewCallback;
    private ViewUILoader mUILoader;
    private RecyclerView mSearchResultRv;
    private AdapterAlbumRv mAdapterAlbumRv;
    private ViewFlowTextLayout mFlowTextLayout;
    private InputMethodManager mImm;
    private ImageView mSearchInpuDeleteBtn;
    private RecyclerView mSuggestWordRv;
    private AdapterSuggestWordRv mAdapterSuggestWordRv;
    private TwinklingRefreshLayout mSearchResultRefreshLayout;
    private boolean mNeedSuggestWord = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initEvent();
        initImpl();
    }

    private void initView() {
        initNavBar(true,"听世界");
        mSearchInpuDeleteBtn = findViewById(R.id.search_input_delete);
        mSearchInpuDeleteBtn.setVisibility(View.GONE);
        mSearchBtn = findViewById(R.id.search_btn);
        mSearchContainer = findViewById(R.id.search_container);
        mSearchInput = findViewById(R.id.search_input);
        mSearchInput.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSearchInput.requestFocus();
                mImm.showSoftInput(mSearchInput, InputMethodManager.SHOW_IMPLICIT);//展示键盘
                UtilLog.d("mImm","展示键盘==>initView");
            }
        },500);


        if (mUILoader ==null) {
            mUILoader = new ViewUILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSussessView();
                }
                @Override
                protected View getEmptyView() {
                    View emptyView = LayoutInflater.from(getContext()).inflate(R.layout.view_empty, this, false);
                    TextView emptyViewText = emptyView.findViewById(R.id.empty_view_text);
                    emptyViewText.setText("没有相关搜索呢，请别强行进行搜索!");
                    return emptyView;
                }

            };
            //mUiLoader与父类解绑，不允许重复绑定
            if (mUILoader.getParent() instanceof ViewGroup) {
                ((ViewGroup) mUILoader.getParent()).removeView(mUILoader);
            }
            mSearchContainer.addView(mUILoader);
        }

    }

    /**
     * 创建数据请求成功的View
     * @return
     */
    private View createSussessView() {
        View resultView = LayoutInflater.from(this).inflate(R.layout.activity_search_result_layout, null);

        //搜索结果
        mSearchResultRv = resultView.findViewById(R.id.search_result_rv);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mSearchResultRv.setLayoutManager(linearLayoutManager);
        mAdapterAlbumRv = new AdapterAlbumRv();
        mSearchResultRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UtilUI.dip2px(view.getContext(), 0);//dp转成px像素
                outRect.bottom = UtilUI.dip2px(view.getContext(), 3);
                outRect.left = UtilUI.dip2px(view.getContext(), 3);
                outRect.right = UtilUI.dip2px(view.getContext(), 3);
            }
        });
        mSearchResultRv.setAdapter(mAdapterAlbumRv);


        //显示联想词的
        mSuggestWordRv = resultView.findViewById(R.id.suggest_word_rv);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        mSuggestWordRv.setLayoutManager(linearLayoutManager1);
        mAdapterSuggestWordRv = new AdapterSuggestWordRv();
        mSuggestWordRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UtilUI.dip2px(view.getContext(), 0);//dp转成px像素
                outRect.bottom = UtilUI.dip2px(view.getContext(), 3);
                outRect.left = UtilUI.dip2px(view.getContext(), 3);
                outRect.right = UtilUI.dip2px(view.getContext(), 3);
            }
        });
        mSuggestWordRv.setAdapter(mAdapterSuggestWordRv);


        //显示热词的
        mFlowTextLayout = resultView.findViewById(R.id.hot_word_view);

        //刷新控件
        mSearchResultRefreshLayout = resultView.findViewById(R.id.search_result_refresh_layout);
        mSearchResultRefreshLayout.setEnableRefresh(false);//禁止下拉刷新
        return resultView;
    }

    private void initEvent() {

        mSearchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mImplSearchLogic.getHotWord();
                    mSearchInpuDeleteBtn.setVisibility(View.GONE);
                    mSearchInput.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSearchInput.requestFocus();
                            mImm.showSoftInput(mSearchInput, InputMethodManager.SHOW_IMPLICIT);//展示键盘
                            UtilLog.d("mImm","展示键盘==>onTextChanged");
                        }
                    },500);
                }else {
                    mSearchInpuDeleteBtn.setVisibility(View.VISIBLE);
                    if (mNeedSuggestWord) {
                        //触发联想查询
                        getSuggestWord(s.toString());
                    }else {
                        mNeedSuggestWord = true;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mSearchInput.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    searchEvent();
                }
                return false;
            }
        });

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEvent();
            }
        });

        mFlowTextLayout.setClickListener(new ViewFlowTextLayout.ItemClickListener() {
            @Override
            public void onItemClick(String text) {
                //不需要相关联想词
                mNeedSuggestWord = false;
                switch2search(text);
            }
        });

        mUILoader.setOnRetryClickListener(new ViewUILoader.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                //隐藏键盘
                mImm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                if (mImplSearchLogic != null) {
                    mImplSearchLogic.reSearch();
                    if (mUILoader != null) {
                        mUILoader.upDateStatus(ViewUILoader.UIStatus.LOADING);
                    }
                }
            }
        });

        mSearchInpuDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchInput.setText("");
            }
        });


        mAdapterSuggestWordRv.setOnItemClickListener(new AdapterSuggestWordRv.OnItemClickListener() {
                @Override
                public void onItemClick(String keyword) {
                    //不需要相关联想词
                    mNeedSuggestWord = false;
                    switch2search(keyword);
                }
        });


        mSearchResultRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                UtilLog.d(TAG,"加载更多... ...");
                    if (mImplSearchLogic != null) {
                        mImplSearchLogic.loadMore();
                    }
            }
        });

        mAdapterAlbumRv.setOnAlbumItemClickListener(new AdapterAlbumRv.OnAlbumItemClickListener() {
            @Override
            public void onAlbumItemClick(int position, Album album) {
                ImplDetailLogic.getInstanceImplDetailLogic().setDetailAlbum(album);
                Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
                startActivity(intent);
            }
        });
    }

    private void searchEvent() {
        //去调用搜索的逻辑
        String keyWord = mSearchInput.getText().toString().trim();
        if (TextUtils.isEmpty(keyWord)) {
            Toast.makeText(SearchActivity.this,"关键字不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //隐藏键盘
        mImm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        if (mImplSearchLogic != null) {
            mImplSearchLogic.doSearch(keyWord);
            if (mUILoader != null) {
                mUILoader.upDateStatus(ViewUILoader.UIStatus.LOADING);
            }
        }
    }

    private void switch2search(String text) {
        //隐藏键盘
        mImm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(this,"关键字不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //把热词扔到输入框
        mSearchInput.setText(text);
        mSearchInput.setSelection(text.length());//设置光标位置
        //发起搜索
        if (mImplSearchLogic != null) {
            mImplSearchLogic.doSearch(text);
            if (mUILoader != null) {
                mUILoader.upDateStatus(ViewUILoader.UIStatus.LOADING);
            }
        }
    }

    private void initImpl() {
        mImm = (InputMethodManager)getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);//键盘

        mImplSearchLogic = ImplSearchLogic.getImplSearchLogic();
        mSearchViewCallback = new SearchViewCallback();
        //注册UI更新的接口
        mImplSearchLogic.registerViewCallback(mSearchViewCallback);
        //去拿热词
        mImplSearchLogic.getHotWord();
    }

    /**
     * 获取联想的关键词
     * @param keyword
     */
    private void getSuggestWord(String keyword) {
        UtilLog.d(TAG,"getSuggestWord ==> "+keyword);
        if (mImplSearchLogic != null) {
            mImplSearchLogic.getSuggestWord(keyword);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImplSearchLogic != null) {
            mImplSearchLogic.unRegisterViewCallback(mSearchViewCallback);
            mImplSearchLogic = null;
        }
    }










    private class SearchViewCallback implements ISearchViewCallback{
        @Override
        public void onSearchResultLoaded(List<Album> result) {
            handleSearchResult(result);
            //隐藏键盘
            mImm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }

        private void handleSearchResult(List<Album> result) {
            hideSuccessView();
            mSearchResultRv.setVisibility(View.VISIBLE);
            if (result != null) {
                if (result.size()==0) {
                    //数据为空
                    if (mUILoader != null) {
                        mUILoader.upDateStatus(ViewUILoader.UIStatus.EMPTY);
                    }
                }else {
                    //数据不为空，设置数据
                    mAdapterAlbumRv.setData(result);
                    if (mUILoader != null) {
                        mUILoader.upDateStatus(ViewUILoader.UIStatus.SUCCESS);
                    }
                }
            }
        }

        @Override
        public void onHotWordLoaded(List<HotWord> hotWordList) {
            hideSuccessView();
            mFlowTextLayout.setVisibility(View.VISIBLE);
            if (mUILoader != null) {
                mUILoader.upDateStatus(ViewUILoader.UIStatus.SUCCESS);
            }
            UtilLog.d(TAG,"热词尺寸 ==> "+hotWordList.size());
            List<String> hotWords = new ArrayList<>();
            hotWords.clear();
            for (HotWord hotWord : hotWordList) {
                String searchWord = hotWord.getSearchword();
                hotWords.add(searchWord);
            }
            Collections.sort(hotWords);
            //更新UI
            mFlowTextLayout.setTextContents(hotWords);
        }

        @Override
        public void onLoadMoreResult(List<Album> result, boolean isOkay) {
            //处理加载更多的结果
            if (mSearchResultRefreshLayout != null) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSearchResultRefreshLayout.finishLoadmore();
                    }
                },500);
            }
            if (isOkay) {
                handleSearchResult(result);
            }else {
                Toast.makeText(SearchActivity.this,"没有更多内容",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onSuggestWordLoaded(List<QueryResult> keyWordList) {
            UtilLog.d(TAG,"联想词尺寸 ==> "+keyWordList.size());
            if (mAdapterSuggestWordRv != null) {
                mAdapterSuggestWordRv.setData(keyWordList);
            }
            if (mUILoader != null) {
                mUILoader.upDateStatus(ViewUILoader.UIStatus.SUCCESS);
            }
            hideSuccessView();
            mSuggestWordRv.setVisibility(View.VISIBLE);
        }

        @Override
        public void onError(int errorCode, String errorMsg) {
            //隐藏键盘
            mImm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            if (mUILoader != null) {
                mUILoader.upDateStatus(ViewUILoader.UIStatus.NETWORK_ERROR);
            }
        }

        private void hideSuccessView(){
            mSuggestWordRv.setVisibility(View.GONE);
            mFlowTextLayout.setVisibility(View.GONE);
            mSearchResultRv.setVisibility(View.GONE);
        }
    }
}
